#include "serverconnection.h"
#include "debug.h"

#include  <unistd.h>

#include <string>
#include <sys/socket.h>
#include <poll.h>

ServerConnection::ServerConnection(int socfd) {
	if ( socfd <= 0 ) {
		debug() << " fd <= 0 .\n " ;
		exit(-1) ;
	}
	socfd_ = socfd ;
}

ServerConnection::~ServerConnection() {
	close(socfd_) ;
}

void ServerConnection::run() {
	while ( true ) {
		std::cout << "input : " ;
		std::string command ;
		std::getline( std::cin , command ) ;
		if ( command == "exit" || command == "quit" ) return ;
		send( command ) ;
		std::cout << recv() ;
	}
}

std::string ServerConnection::recv() {
	std::string result ;
	int len = read( socfd_ , buffer , BUFSIZ ) ;
	buffer[len] = 0 ;
	result  += std::string(buffer) ;
	while ( len == BUFSIZ ) {
		struct pollfd pfd = { .fd = socfd_ , .events = POLLIN } ;
		if ( poll( &pfd , 1 , 0 ) == 0 ) break ;
		len = read( socfd_ , buffer , BUFSIZ ) ;
		buffer[len] = 0 ;
		result  += std::string(buffer) ;
	}
	return result ;
}

void ServerConnection::send(const std::string &command) {
	int len = write( socfd_ , command.data() , command.size() ) ;
}
